package com.icss.service.login;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import com.icss.helper.BatchSql;
import com.icss.service.BaseService;

/**
 * 登陆相关功能
 * @author shixiaolong
 * Jun 7, 2012
 */
public class LoginService extends BaseService{
	
	/**
	 * @param request
	 * @return
	 */
	public int login(HttpServletRequest request){
		String username = req.getValue(request, "username");
		String password = req.getValue(request, "password");
		String irand = req.getValue(request, "irand");//验证码
		//首先判断账户是否存在
		String sql="select count(1) from tbl_user where nickname=? and userstate=1 ";
		int result = db.queryForInt(sql,new Object[]{username});
		if(result!=1){
			//用户不存在
			return -1;
		}
		sql="select count(1) from tbl_user where nickname=? and password=fn_md5(?) and userstate=1 ";
		result = db.queryForInt(sql,new Object[]{username,password});
		if(result!=1){
			//密码不正确
			String pwwrong_flag = (String)request.getSession().getAttribute("pwwrong_flag");
			if(pwwrong_flag==null||"".equals(pwwrong_flag)){
				
			}
			
			request.setAttribute("username", username);
			this.recordLoginHisFail(username, request);
			return -2;
		}
		String rand = (String)request.getSession().getAttribute("rand");
		if(!irand.equals(rand)){
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			this.recordLoginHisFail(username, request);
			//验证码错误
			return -3;
		}
		//设置session 时间 单位：秒
		request.getSession().setMaxInactiveInterval(1800);
		log.debug("该“"+req.getValue(request, "username")+"”用户登陆，会话有效时间为半个小时！");
		//把用户信息放入session 中
		 sql="select * from tbl_user where nickname=? ";
		Map user = db.queryForMap(sql,new Object[]{username});
		request.getSession().setAttribute("user",user);
		
		this.recordLoginHisSuccess(user, request);
		return 1;
	}
	
	/**
	 * 登陆流水成功
	 */
	public void recordLoginHisSuccess(Map user,HttpServletRequest request){
		String ipaddress = this.getIpAddr(request);
		String userid= str.get(user, "USERID");
		String sql="insert into tbl_login_his(user_id,login_date,is_success,ip_address) values(?,sysdate,1,?)";
		int result = db.update(sql,new Object[]{userid,ipaddress});
		//如果登陆不成功，保存日志
		if(result!=1){
			log.error("----登陆流水入库失败---");
		}
	}
	
	/**
	 * 登陆流水失败
	 */
	public void recordLoginHisFail(String username,HttpServletRequest request){
		String ipaddress = this.getIpAddr(request);
		String sql="insert into tbl_login_his(nickname,login_date,is_success,ip_address) values(?,sysdate,0,?)";
		int result = db.update(sql,new Object[]{username,ipaddress});
		//如果登陆不成功，保存日志
		if(result!=1){
			log.error("----登陆流水入库失败---");
		}
	}
	
	/**
	 * 获取客户端的真实地址
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();
	    }
	    return ip;
	}
	
	/**
	 * 退出登陆
	 * @return
	 */
	public String loginOff(HttpServletRequest request){
        HttpSession session = request.getSession();
		session.removeAttribute("user");
		session.invalidate();
	 
		
		return "error";
	}
	
	/**
	 * 密码修改
	 * @return
	 */
	public int changePassword(HttpServletRequest request){
		String new_password_1 = req.getValue(request, "new_password_1"); 
		String new_password_2 = req.getValue(request, "new_password_2");
		String current_password = req.getValue(request, "current_password");
		String currentpassword = db.queryForString("select fn_md5(?) from dual",new Object[]{current_password});
		Map user = (Map)request.getSession().getAttribute("user");
		String userid = str.get(user, "USERID");
		String old_password = str.get(user, "PASSWORD");
		if(!currentpassword.equals(old_password)){
			return -1;
		}
		if(!new_password_1.equals(new_password_2)){
			request.setAttribute("current_password", current_password);
			return -2;
		}else{

			String new_password = db.queryForString("select fn_md5(?) from dual",new Object[]{new_password_1});
			BatchSql batchSql = new BatchSql();
			String sql="update tbl_user set password = ? where userid = ? and userstate = 1 ";
			batchSql.addBatch(sql,new Object[]{new_password,userid});
			sql="insert into tbl_password_mod_log(userid,modify_date,old_password,new_password) " +
					" values(?,sysdate,?,?)";
			batchSql.addBatch(sql,new Object[]{userid,old_password,new_password});
			int result = db.doInTransaction(batchSql);
			if(result!=1){
				log.debug("-------密码修改保存失败----------");
				return -3;
			}else{
				 sql="select * from tbl_user where userid=? ";
				 user = db.queryForMap(sql,new Object[]{userid});
				 request.getSession().setAttribute("user",user);
				return 1;
			}
		}
		
	}

}
